package site.marqstree.latte.core.delegates.web.route;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.webkit.URLUtil;
import android.webkit.WebView;
import androidx.core.content.ContextCompat;
import site.marqstree.latte.core.delegates.LatteDelegate;
import site.marqstree.latte.core.delegates.web.WebDelegate;
import site.marqstree.latte.core.delegates.web.WebDelegateImpl;

/*
 * 项目名: EleCommerce
 * 包名: site.marqstree.latte.core.delegates.web.route
 * 文件名: Router
 * 创建者: marqstree
 * 创建时间: 2020/1/31 11:39
 * 描述: 路由工具类
 * 处理WebView内部的url跳转
 * 采用创建新的含WebView的Fragment的方式，代替浏览器内部url跳转
 */
public class Router {

    private Router() {
    }

    private static class Holder {
        private static final Router INSTANCE = new Router();
    }

    public static Router getInstance() {
        return Holder.INSTANCE;
    }

    //处理传给WebView的url
    //若是电话url,调用电话服务
    //若是http url，则采用创建新的含WebView的Fragment的方式，代替浏览器内部url跳转
    public final boolean handleWebUrl(WebDelegate delegate, String url) {

        //如果是电话协议
        if (url.contains("tel:")) {
            callPhone(delegate.getContext(), url);
            return true;
        }

        //获取WebView所在Fragment的父Fragment(带底部Tab导航按钮的Fragment)
        final LatteDelegate topDelegate = delegate.getTopDelegate();

        //创建新的含一个WebView的Fragment
        final WebDelegateImpl webDelegate = WebDelegateImpl.create(url);
        //用新的含WebView的Fragment替换原来的父Fragment(带底部Tab导航按钮的Fragment)
        topDelegate.getSupportDelegate().start(webDelegate);

        return true;
    }

    private void loadWebPage(WebView webView, String url) {
        if (webView == null)
            throw new NullPointerException("WebView is null!");

        webView.loadUrl(url);
    }

    private void loadLocalPage(WebView webView, String url) {
        loadWebPage(webView, "file:///android_asset/" + url);
    }

    private void loadPage(WebView webView, String url) {
        //若是有"http://"或"https://"前缀的url，直接传入WebView
        if (URLUtil.isNetworkUrl(url) ) {
            loadWebPage(webView, url);
        }
        //若是以"file:///android_asset/"开头的url，直接传入WebView
        else if(URLUtil.isAssetUrl(url)) {
            loadWebPage(webView, url);
        }
        //若没有域名或"file:///android_asset/"前缀，则视为访问本地html文件
        //在文件名前补全"file:///android_asset/"前缀，拼装成完整的本地url，再传入WebView
        else {
            loadLocalPage(webView, url);
        }
    }

    public final void loadPage(WebDelegate delegate, String url) {
        loadPage(delegate.getWebView(), url);
    }

    private void callPhone(Context context, String uri) {
        final Intent intent = new Intent(Intent.ACTION_DIAL);
        final Uri data = Uri.parse(uri);
        intent.setData(data);
        ContextCompat.startActivity(context, intent, null);
    }
}